package com.hudak.user;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
	@Autowired
	private UserRepository userRepository;

	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}
	
	public boolean mobileExist(String mobile){
		User user = userRepository.findByMobile(mobile);
		return user != null;
	}
	
	
	public String getDefaultUsername(String mobile){
		try {
			String username = "ksd"+mobile.substring(0, 3)+"xxxx"+mobile.substring(7);
			return username;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static  boolean isMobile(String mobile){
		Pattern p = Pattern.compile("^(1[0-9])\\d{9}$");
		Matcher m = p.matcher(mobile);
		return m.matches();
	}
	
	public User findByAccount(String account){
		User user = null;
		boolean isMobile = isMobile(account);
		if (isMobile) {
			user = userRepository.findByMobile(account);
			
		}else{
			user = userRepository.findByUsername(account);
		}
		return user;
	}
	public String getSalt(String account){
		User user = findByAccount(account);
		String salt="";
		if (user != null) {
			salt = user.getSalt();
		}
		return salt; 
		
	}
}
